﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Foggy.Users
{
    using Foggy.Data;
    using Foggy.Data.Users;

    public class UserService : IUserService
    {
        public IEnumerable<User> GetUsers()
        {
            List<UserDto> userDtos;
            
            using (var context = new FoggyContext())
            {
                userDtos = context.Users.ToList();
            }

            var users = userDtos.Select(u => new User { Name = u.Name, Email = u.Email });
            return users;
        }

        public void SaveUsers(IEnumerable<User> users)
        {
            if (users == null)
            {
                return;
            }

            // TODO: use CSLA and deleted flags
            using (var context = new FoggyContext())
            {
                foreach (var user in users)
                {
                    var user1 = user;
                    var existingUserDto = context.Users.FirstOrDefault(u => u.Email == user1.Email);

                    if (existingUserDto == null)
                    {
                        context.Users.Add(new UserDto { Email = user.Email });
                    }                    
                }

                foreach (var userDto in context.Users)
                {
                    var user1 = userDto;
                    var existingUser = users.FirstOrDefault(u => u.Email == user1.Email);

                    if (existingUser == null)
                    {
                        context.Users.Remove(userDto);
                    }
                }

                context.SaveChanges();
            }
        }
    }
}